import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel

from user_service import UserService
from database import create_tables, get_conn, Product, Employee

app = FastAPI()
userService = UserService()


class UserLoginReq(BaseModel):
    username: str
    password: str


class RegisterReq(BaseModel):
    name: str
    email: str
    phone: str
    employee_no: str


# helloworld
@app.post("/login", tags=["login"], description="user login")
async def login(user_login_req: UserLoginReq):
    userService.login(email=user_login_req.username, password=user_login_req.password)
    return {"message": "Hello World 2"}


@app.post("/register", tags=[""])
async def register(user_req: RegisterReq):
    userService.register(name=user_req.name, email=user_req.email, phone=user_req.phone,
                         employee_no=user_req.employee_no)
    return {"message": "register success"}


# 路径参数:/item/10000 , /item/1002
@app.get("/items/{sku}")
async def sku_info(sku):
    return {"sku": sku}


# 查询参数: /product/list?page=1&pagesize=100&filter=red
@app.get("/product/list")
async def product_list(page, size):
    my_list = [
        {"sku": "BMW", "price": 100, "page": page, "size": size},
        {"sku": "dz", "price": 1000, "page": page, "size": size},
    ]
    return my_list


# 发布一个商品
class MyProduct(BaseModel):
    sku: str
    price: float
    description: str


@app.post("/product/creat")
async def product_creat(product: MyProduct):
    print("request body:", product.dict())
    return "ok"


if __name__ == '__main__':
    # create_tables()
    p1 = Product(sku="BMW-X7", sku_name="BMW", sku_price=13000)
    # Conn.add(p1)
    # Conn.commit()
    db_p = get_conn().query(Product).first()
    print(db_p.sku, db_p.sku_name, db_p.sku_price)
    seazen = Employee(name="seazen", email="seazen.ext@zeiss.com", phone="17716778998", employee_no="e-12339")
    # Conn.add(seazen)
    # Conn.commit()
    mathew = Employee(name="mathew", email="mathew.ext@mathew.com", phone="1781678899", employee_no="e-1199")
    # Conn.add(mathew)
    # Conn.commit()
    cn = get_conn()
    xx = cn.query(Employee).filter_by(name="mathew").first()
    print(xx.employee_no, xx.name, xx.phone)
    xx.phone = "1781678891"
    cn.commit()
